/**
 * Copyright (C) 2015-2018 IQIYI
 * All rights reserved.
 *
 * Author     : 王海斌
 * E-mail     : wanghaibin@qiyi.com
 * Version    :
 * Date       : Tue 20 Nov 2018 10:57:24 AM CST
 * Destription:
 *
 */

#include <iostream>
 #include <stdio.h>
using namespace std;

class ClTest
{
public:
    ClTest (){}
    virtual ~ClTest (){}

private:
    int data;
};

void ReleaseTest(ClTest *& t)
{
    if(t) {
        delete t;
        t = NULL;
    }
}

void GetTest(ClTest *& t2)
{
    ClTest * t1 = new ClTest;
    t2 = t1;
    printf("t2in=%p\n", t2);
}

//int main(int argc, char *argv[])
//{
//
//    ClTest * t1 = new ClTest;
//
//    printf("t1=%p\n", t1);
//    ReleaseTest(t1);
//    printf("t1=%p\n", t1);
//    ClTest * t2 = NULL;
//    printf("t2=%p\n", t2);
//    GetTest(t2);
//    printf("t2=%p\n", t2);
//
//    int *p2 = new int [1];
//
//    cout << "t1=" << endl;
//
//    bool * bTest = new bool;
//    *bTest = false;
//    cout << "bTest=" << *bTest <<endl;
//
//    return 0;
//}

#include <stdio.h>

#include <stdlib.h>
#include <string.h>

int setChunkSize(size_t chunksize, int obj_size) {
#define MEM_PAGE_SIZE 4096
#define MEM_MIN_FREE  32
#define MEM_MAX_FREE  65535
#define MEM_CHUNK_MAX_SIZE 256*1024
    int cap;
    size_t csize = chunksize;

    csize = ((csize + MEM_PAGE_SIZE - 1) / MEM_PAGE_SIZE) * MEM_PAGE_SIZE;  /* round up to page size */
    cap = csize / obj_size;

    if (cap < MEM_MIN_FREE)
        cap = MEM_MIN_FREE;
    if (cap * obj_size > MEM_CHUNK_MAX_SIZE)
        cap = MEM_CHUNK_MAX_SIZE / obj_size;
    if (cap > MEM_MAX_FREE)
        cap = MEM_MAX_FREE;
    if (cap < 1)
        cap = 1;
    printf("cur cap=%d\n", cap);

    csize = cap * obj_size;
    csize = ((csize + MEM_PAGE_SIZE - 1) / MEM_PAGE_SIZE) * MEM_PAGE_SIZE;  /* round up to page size */
    cap = csize / obj_size;

    printf("chunk_capacity=%d, chunk_size=%d\n", cap, csize);
    return cap;
}

void * freeList;

void *get() {
    void** Free = (void **)freeList;
    freeList = *Free;
    *Free = NULL;
    return Free;
}

int main(void)
{
    int obj_size = 36;
    int chunk_capacity = setChunkSize(4096, obj_size);
    freeList = calloc(4096,1);
    memset(freeList, 'a', 4096);
    void **Free = (void **)freeList;
    printf("freeList=%p, Free=%p, (*Free)=%p\n", freeList, Free, *Free);
    for (int i = 1; i < chunk_capacity; ++i) {
        *Free = (void *) ((char *) Free + obj_size);
        void **nextFree = (void **)*Free;
        printf("i=%d, Free=%p nexFree=%p, *Free=%p (*nextFree)=%p\n", i, Free, nextFree, *Free, *nextFree);
        Free = nextFree;
    }
    for(int i=0; i<4096; i++) {
        char * p = (char*)freeList+i;
        printf("mi=%d\n",*p);
    }
    printf("get addr1=%p\n", get());
    printf("freeList=%p\n", freeList);
    printf("get addr2=%p\n", get());
    printf("freeList=%p\n", freeList);
    //free(freeList);
    return 0;
}

